#!/usr/bin/env node
const { program } = require('commander');
const shell = require('shelljs');
const fs = require('fs');
const path = require('path');
let inquirer;
const red = '\x1b[31m';
const yellow = '\x1b[33m';
const blue = '\x1b[34m';
const reset = '\x1b[0m';
const green = '\x1b[32m';

program
    .arguments('<env>')
    .option('-f, --filter <packages>', 'Packages to deploy')
    .action(async (env, options) => {
        checkGitStatus()
        let packages = options.filter ? options.filter.split(',') : [];
        if (packages.length === 0) {
            inquirer = inquirer || (await import('inquirer')).default;
            const appsDir = path.join(__dirname, '../apps'); // adjust the path as needed
            const choices = fs.readdirSync(appsDir).filter(file => fs.statSync(path.join(appsDir, file)).isDirectory());
            inquirer.prompt([
                {
                    type: 'checkbox',
                    message: '请选择你需要发布的包',
                    name: 'packages',
                    choices: ['ALL', ...choices], // 在选项中添加 "ALL"
                },
            ]).then(answers => {
                if (answers.packages.includes('ALL')) {
                    packages = choices; // 如果选择了 "ALL"，则选择所有的包
                } else {
                    packages = answers.packages;
                }
                writeConfigAndCommit(env, packages);
            });
        } else {
            writeConfigAndCommit(env, packages);
        }
    });

program.parse(process.argv);
//     jdk
function writeConfigAndCommit(env, packages) {
    const currentBranch = shell.exec('git branch --show-current').stdout.trim();
    const deployBranch = env === 'dev' ? 'dev' : 'master'
    shell.exec(`git push origin ${currentBranch}`);
    shell.exec(`git checkout ${deployBranch}`);
    shell.exec(`git pull origin ${currentBranch}`)
    shell.exec(`git push origin ${deployBranch}`);
    const version = shell.exec('git rev-parse HEAD').stdout.trim().substring(0, 9); // 修改这里
    const tagPrefix = env === 'dev' ? 'dev' : 'prod';
    const tagName = `${tagPrefix}-${version}-${packages.join('-')}`;
    shell.exec(`git tag ${tagName}`);
    shell.exec(`git push origin ${tagName}`); 
    
    shell.exec(`git checkout ${currentBranch}`);
    console.log(green + packages.toString() + '自动触发部署完成✅')
}
function checkGitStatus() {
    const gitStatus = shell.exec('git status --porcelain', { silent: true }).stdout;
    if (gitStatus) {
        console.log(yellow + '当前有未提交的更改，请先`git add .`并`git commit`提交你的更改，或者git stash你的更改。' + reset);
        process.exit(1);
    }
}